package com.hunttown.mes.manage.service;

import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.common.cache.Cache;
import com.hunttown.mes.common.utils.StringUtils;
import com.hunttown.mes.rpc.api.AnalysisWebsiteParamRpcService;
import com.hunttown.mes.rpc.domain.AnalysisWebsiteParamDTO;
import com.hunttown.mes.rpc.domain.query.AnalysisWebsiteParamDTOQuery;
import com.hunttown.common.domain.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * created by wangjunfu on 2018-11-26 15:07:24
 */
@Service
public class AnalysisWebsiteParamManageService {

    private final static Logger logger = LoggerFactory.getLogger(AnalysisWebsiteParamManageService.class);

    private final AnalysisWebsiteParamRpcService rpcService;
    private final Cache jedisCache;

    @Autowired
    public AnalysisWebsiteParamManageService(AnalysisWebsiteParamRpcService rpcService, Cache jedisCache) {
        this.rpcService = rpcService;
        this.jedisCache = jedisCache;
    }

    // 新增
    public AnalysisWebsiteParamDTO insert(AnalysisWebsiteParamDTO objDTO) {
        return rpcService.insert(objDTO);
    }

    // 通过ID修改
    public Boolean updateInfoById(AnalysisWebsiteParamDTO objDTO) {
        Boolean isNext = rpcService.updateInfoById(objDTO);
        if (isNext) {
            // 刷新缓存
            refreshWebsiteCacheAll(objDTO.getId());
        }
        return isNext;
    }

    // 通过Query修改
    public Boolean updateInfoByQuery(AnalysisWebsiteParamDTOQuery objDTOQuery) {
        Boolean isNext = rpcService.updateInfoByQuery(objDTOQuery);

        //单个更新
        if (isNext && objDTOQuery.getW_id() != null) {
            refreshWebsiteCacheAll(objDTOQuery.getW_id());
        }

        //批量更新
        if (isNext && objDTOQuery.getIds() != null) {
            // 刷新缓存
            List<Integer> list = new ArrayList<>();
            try {
                list = (List<Integer>) objDTOQuery.getIds();
            } catch (Exception e) {
                e.printStackTrace();
            }
            refreshWebsiteCacheByIdList(list);
        }

        return isNext;
    }

    // 通过ID删除
    public Boolean delete(Integer id) {
        Boolean isNext = rpcService.deleteById(id);

        if (isNext) {
            // 刷新缓存
            refreshWebsiteCacheAll(id);
        }
        return isNext;
    }

    // 通过ID获取
    public AnalysisWebsiteParamDTO getById(Integer id) {
        if (id <= 0) {
            return null;
        }
        return rpcService.selectById(id);
    }

    //根据企业ID获取数据
    public AnalysisWebsiteParamDTO getByEntId(Integer entId) {
        AnalysisWebsiteParamDTOQuery query = new AnalysisWebsiteParamDTOQuery();
        query.setEntId(entId);
        return getByQuery(query);
    }

    /**
     * 通过ID，从缓存中获取
     *
     * @param entId 企业ID
     * @return obj
     */
    public AnalysisWebsiteParamDTO getFromCacheEntId(Integer entId) {
        if (entId == null || entId <= 0) {
            return null;
        }

        AnalysisWebsiteParamDTO obj = jedisCache.oget(KeyConstants.WEBSITE_INFO_CACHE_KEY_ENTID + entId, AnalysisWebsiteParamDTO.class);
        if (obj == null) {
            obj = getByEntId(entId);
            if (obj != null) {
                jedisCache.oset(KeyConstants.WEBSITE_INFO_CACHE_KEY_ENTID + entId, obj);
            }
        }

        return obj;
    }

    //根据根域名获取网站配置
    private AnalysisWebsiteParamDTO getWebsiteByDomain(HttpServletRequest request, String pin) {

        //region [1].先拿企业ID获取，如果获取不到（登录状态），拿domain获取
        int entId = jedisCache.get(KeyConstants.WEBSITE_CURRENT_ENTERPRISE_ID + pin, -1);
        if (entId > 0) {
            AnalysisWebsiteParamDTO obj = getFromCacheEntId(entId);
            if (obj != null) {
                return obj;
            }
        }
        //endregion

        //region [2].使用domain获取
        StringBuffer url = request.getRequestURL();
        Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE);
        Matcher matcher = p.matcher(url);

        String domain = "";

        while (matcher.find()) {
            domain = matcher.group();
            if (StringUtils.isNotBlank(domain)) {
                System.out.println(domain);
                break;
            }
        }

        if (StringUtils.isNotBlank(domain)) {
            AnalysisWebsiteParamDTO obj = jedisCache.oget(KeyConstants.WEBSITE_INFO_CACHE_KEY_DOMAIN + domain, AnalysisWebsiteParamDTO.class);
            if (obj == null) {
                obj = rpcService.selectByDomain(domain);
                if (obj != null) {
                    jedisCache.oset(KeyConstants.WEBSITE_INFO_CACHE_KEY_DOMAIN + domain, obj);
                }
            }
            return obj;
        }
        //endregion

        return null;
    }

    // 从缓存中获取网站名称（简称）
    public String getWebsiteNameFromCache(HttpServletRequest request, String pin) {
        AnalysisWebsiteParamDTO obj = getWebsiteByDomain(request, pin);
        return obj == null ? KeyConstants.DEFAULT_COMPANY_INFO : obj.getSiteName();
    }

    // 从缓存中获取网站名称（全称）
    public String getWebsiteFullNameFromCache(HttpServletRequest request, String pin) {
        AnalysisWebsiteParamDTO obj = getWebsiteByDomain(request, pin);
        return obj == null ? KeyConstants.DEFAULT_COMPANY_INFO : obj.getSiteNameFull();
    }

    // 从缓存中获取站点版权信息
    public String getWebsiteCopyrightFromCache(HttpServletRequest request, String pin) {
        AnalysisWebsiteParamDTO obj = getWebsiteByDomain(request, pin);
        return obj == null ? KeyConstants.DEFAULT_COMPANY_COPYRIGHT : obj.getCopyRight();
    }

    // 通过Query获取
    public AnalysisWebsiteParamDTO getByQuery(AnalysisWebsiteParamDTOQuery objDTOQuery) {
        return rpcService.selectObjByQuery(objDTOQuery);
    }

    // 获取分页列表
    public Page<AnalysisWebsiteParamDTO> getForPage(AnalysisWebsiteParamDTOQuery objDTOQuery) {
        return rpcService.getListForPage(objDTOQuery);
    }

    // 刷新缓存
    private void refreshWebsiteCacheAll(Integer id) {
        if (id == null || id <= 0) {
            return;
        }

        AnalysisWebsiteParamDTO obj = getById(id);
        if (obj != null) {
            jedisCache.delete(KeyConstants.WEBSITE_INFO_CACHE_KEY_ENTID + obj.getEntId());
            jedisCache.delete(KeyConstants.WEBSITE_INFO_CACHE_KEY_DOMAIN + obj.getSiteUrl());
        }
    }

    private void refreshWebsiteCacheByIdList(List<Integer> idList) {
        if (idList == null || idList.size() == 0) {
            return;
        }

        for (Integer id : idList) {
            refreshWebsiteCacheAll(id);
        }
    }
}